package com.taokatao.cardmee.business;

import android.Manifest;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.taokatao.cardmee.App;
import com.taokatao.cardmee.BaseActivity;
import com.taokatao.cardmee.C;
import com.taokatao.cardmee.R;
import com.taokatao.cardmee.Utils;
import com.taokatao.cardmee.WebActivity;
import com.taokatao.cardmee.api.ApiManager;
import com.taokatao.cardmee.api.RespWrapper;
import com.taokatao.cardmee.api.SubscriberAdapter;
import com.taokatao.cardmee.api.model.CardFDMyCourseInfo;
import com.taokatao.cardmee.api.security.ServiceUrlProvider;
import com.taokatao.cardmee.business.cardcrud.CardAddByCodeActivity;
import com.taokatao.cardmee.business.carddetail.CardFDSignActivity;
import com.taokatao.cardmee.common.widget.AlertDialog;
import com.taokatao.cardmee.db.model.Card;
import com.taokatao.cardmee.db.model.CardStore;
import com.yanzhenjie.permission.AndPermission;
import com.yanzhenjie.permission.PermissionListener;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import me.dm7.barcodescanner.zbar.Result;
import me.dm7.barcodescanner.zbar.ZBarScannerView;


/**
 * 通用的扫描界面，完成对特定格式的二维码进行处理
 */
public class CommonScanActivity extends BaseActivity implements ZBarScannerView.ResultHandler, View.OnClickListener {

    private static final int REQUEST_CODE_CAMERA = 66;

    @BindView(R.id.view_zbar_scanner) ZBarScannerView mScannerView;
    @BindView(R.id.v_fit) View vFit;
    @BindView(R.id.i_back) ImageView iBack;
    @BindView(R.id.i_light) ImageView iLight;
    @BindView(R.id.t_title) TextView tTitle;
    @BindView(R.id.t_scan_result) TextView tScanResult;

    private boolean isLightMode;

//    private AlertDialog dlgError;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_common_scan);
        ButterKnife.bind(this);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            final int statusBarHeight = Utils.calcStatusBarHeight(this);
            vFit.getLayoutParams().height += statusBarHeight;
        }

        tTitle.getPaint().setFakeBoldText(true);
        String sTitle = getIntent().getStringExtra("extra_name");
        if (TextUtils.isEmpty(sTitle)) {
            sTitle = "扫一扫";
        }
        tTitle.setText(sTitle);

//        RxPermissions rxPermissions = new RxPermissions(this);
//        rxPermissions
//                .request(Manifest.permission.CAMERA)
//                .subscribe(new Action1<Boolean>() {
//                    @Override
//                    public void call(Boolean granted) {
//                        if (granted) { // Always true pre-M
//                            // I can control the camera now
//                            Toast.makeText(getApplicationContext() , "I can control the camera now" , Toast.LENGTH_SHORT).show();
//                        } else {
//                            // Oups permission denied
//                            Toast.makeText(getApplicationContext() , "Oups permission denied" , Toast.LENGTH_SHORT).show();
//                        }
//                    }
//                });

        if (!AndPermission.hasPermission(this, Manifest.permission.CAMERA)) {
            AndPermission.with(this)
                    .requestCode(REQUEST_CODE_CAMERA)
                    .permission(Manifest.permission.CAMERA)
                    .send();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        AndPermission.onRequestPermissionsResult(requestCode, permissions, grantResults, listener);
    }

    private PermissionListener listener = new PermissionListener() {
        @Override
        public void onSucceed(int requestCode, List<String> grantedPermissions) {
            // Toast.makeText(getApplicationContext(), "onSucceed " + requestCode + "##", Toast.LENGTH_SHORT).show();
            // 权限申请成功回调。
        }

        @Override
        public void onFailed(int requestCode, List<String> deniedPermissions) {
            // 权限申请失败回调。
            // Toast.makeText(getApplicationContext(), "onFailed " + requestCode + "##", Toast.LENGTH_SHORT).show();
            // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
            if (AndPermission.hasAlwaysDeniedPermission(CommonScanActivity.this, deniedPermissions)) {
                // 第一种：用默认的提示语。
                AndPermission.defaultSettingDialog(CommonScanActivity.this, REQUEST_CODE_CAMERA).show();
            } else {
                new AlertDialog.Builder(CommonScanActivity.this).setTitle("权限提示")
                        .setMessage("您好，卡蜜需要获得相机权限才来打开您手机的摄像头进行对条形码、二维码的识别扫描。如果为误触拒绝，重新进入此界面即可。")
                        .setPositiveButton("知道了", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                                finish();
                            }
                        }).setCancelable(false).create().show();
            }
        }
    };

    @Override
    @OnClick({R.id.i_back, R.id.i_light})
    public void onClick(View v) {
        if (v == iBack) {
            onBackPressed();
        } else if (v == iLight) {
            Utils.onMobEvent(this, "clickFlashlight");
            isLightMode = !isLightMode;
            mScannerView.setFlash(isLightMode);
        }
    }

    @Override
    public void handleResult(Result rawResult) {
        // Do something with the result here
        String format = rawResult.getBarcodeFormat().getName();
        String content = rawResult.getContents();
        Utils.logd("handleResult type:%s #content:%s", format, content);
        // If you would like to resume scanning, call this method below:
        // mScannerView.resumeCameraPreview(this);

        Utils.logd("handleResult before handleScanResult");
        handleScanResult(content);
        Utils.logd("handleResult after handleScanResult");
    }


    @Override
    protected void onResume() {
        super.onResume();
        mScannerView.setResultHandler(this); // Register ourselves as a handler for scan results.
        mScannerView.startCamera();          // Start camera on resume

//        mScannerView.postDelayed(runFuncCheck, 1500);
    }

//    final Runnable runFuncCheck = new Runnable() {
//        @Override
//        public void run() {
//            Utils.loge("CardCodeScanActivity onResume scanner post getChildCount %d", mScannerView.getChildCount());
//
//            // 有权限的时候childCount是22#没有权限的时候childCount是20
//            if (mScannerView.getChildCount() < 2 && !isFinishing()) {
//                showErrorDialog();
//            }
//        }
//    };

//    private void showErrorDialog() {
//        if (dlgError == null) {
//            dlgError = new AlertDialog.Builder(this).setTitle("提示").setMessage("无法打开摄像头，请检查是否给卡蜜开启了相关权限")
//                    .setCancelable(false)
//                    .setPositiveButton("知道了", new DialogInterface.OnClickListener() {
//                        @Override
//                        public void onClick(DialogInterface dialog, int which) {
//                            finish();
//                        }
//                    }).create();
//        }
//        dlgError.show();
//    }

    @Override
    protected void onPause() {
        super.onPause();
        mScannerView.stopCamera();           // Stop camera on pause

//        mScannerView.removeCallbacks(runFuncCheck);
        mScannerView.removeCallbacks(runRecoverScan);
    }

    /**
     * 处理扫描的结果
     */
    private void handleScanResult(String content) {
        if (TextUtils.isEmpty(content)) return;
//        http://wap.taokatao.cn:64559/wapServer/bussiness/downAddSign.do?storeId=1(测试)
//        http://c.flow360.cn:4559/wapServer/bussiness/downAddSign.do?storeId=1(正式)
        boolean findResult = false;
        final String sDealWithApp = ServiceUrlProvider.obtainStoreQRCodeUrl();
        if (content.startsWith(sDealWithApp)) {
            try {
                String argString = content.split("\\?")[1];
                String[] argArray = argString.split("&");
                for (String arg : argArray) {
                    if (arg.startsWith("storeId=")) {
                        findResult = true;
                        long storeId = Long.parseLong(arg.substring("storeId=".length()));
                        requestAddSign(storeId);
                        break;
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        // 不是卡蜜内部分店的码
        if (!findResult) {
            if (content.startsWith("http://") || content.startsWith("https://")) {
                // 如果是http开头  打卡新界面
                Intent intent = new Intent(this, WebActivity.class);
                intent.putExtra("extra_url", content);
                startActivity(intent);
                finish();
            } else {
                // 当做自定义卡来添加
                Intent intent = new Intent(this, CardAddByCodeActivity.class);
                CardStore customStore = new CardStore();
                customStore.setBusinessId(C.settings.BUSINESS_OTHER_ID);
                intent.putExtra("extra_card_store", customStore);
                intent.putExtra("extra_card_code", content);
                startActivity(intent);
                finish();
            }
        }
    }


    private void requestAddSign(long storeId) {
        ApiManager.i().addSign(this, App.i().getCurrUser().getUuid(), storeId, new SubscriberAdapter<RespWrapper<String>>() {
            @Override
            public void onNext(RespWrapper<String> o) {
                super.onNext(o);
                if (o.code == C.http.RESULT_CODE_SUCCESS) {
                    if ("1".equals(o.message)) {
                        Intent intent = new Intent(CommonScanActivity.this, CommonReceiveInfoActivity.class);
                        Card card = App.i().getGson().fromJson(o.justDecryptDataValue(), Card.class);
                        intent.putExtra("extra_card_info", card);
                        startActivity(intent);
                        finish();
                    } else if ("2".equals(o.message)) {
                        Intent intent = new Intent(CommonScanActivity.this, CardFDSignActivity.class);
                        List<CardFDMyCourseInfo> dataList =
                                App.i().getGson().fromJson(o.justDecryptDataValue(), new TypeToken<List<CardFDMyCourseInfo>>() {
                                }.getType());
                        intent.putExtra("extra_course_list", App.i().getGson().toJson(dataList));
                        startActivity(intent);
                        finish();
                    }
                } else {
                    mScannerView.postDelayed(runRecoverScan, 2500);
                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                mScannerView.postDelayed(runRecoverScan, 2500);

            }
        }.showProgress(this));
    }


    // 3码合1
    @Deprecated
    static class ScanCardInfo {
        public long storeId;
        public int type;
    }

    // 3码合1
    @Deprecated
    private void requestScanToAddMemberCard(long storeId) {
        ApiManager.i().scanToAddMemberCard(this, App.i().getCurrUser().getUuid(), storeId, new SubscriberAdapter<RespWrapper<Card>>() {
            @Override
            public void onNext(RespWrapper<Card> o) {
                super.onNext(o);
                if (o.code == C.http.RESULT_CODE_SUCCESS) {
                    Intent intent = new Intent(CommonScanActivity.this, CommonReceiveInfoActivity.class);
                    intent.putExtra("extra_card_info", o.decode(Card.class));
                    startActivity(intent);
                    finish();
                } else {
                    mScannerView.postDelayed(runRecoverScan, 2500);
                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                mScannerView.postDelayed(runRecoverScan, 2500);

            }
        }.showProgress(this));
    }

    // 3码合1
    @Deprecated
    private void requestUserActiveSign(long sid) {
        ApiManager.i().userActiveSign(this, App.i().getCurrUser().getUuid(), sid, new SubscriberAdapter<RespWrapper<List<CardFDMyCourseInfo>>>() {
            @Override
            public void onNext(RespWrapper<List<CardFDMyCourseInfo>> o) {
                super.onNext(o);
                if (o.code == C.http.RESULT_CODE_SUCCESS) {
                    Intent intent = new Intent(CommonScanActivity.this, CardFDSignActivity.class);
                    List<CardFDMyCourseInfo> dataList = o.decode(new TypeToken<List<CardFDMyCourseInfo>>() {
                    }.getType());
                    intent.putExtra("extra_course_list", App.i().getGson().toJson(dataList));
                    startActivity(intent);
                    finish();
                } else {
                    mScannerView.postDelayed(runRecoverScan, 2500);
                }
            }

            @Override
            public void onError(Throwable e) {
                super.onError(e);
                mScannerView.postDelayed(runRecoverScan, 2500);
            }
        }.showProgress(this));
    }

    private final Runnable runRecoverScan = new Runnable() {
        @Override
        public void run() {
            mScannerView.resumeCameraPreview(CommonScanActivity.this);
        }
    };
}